package net.sakz.oss;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

public class LoginOutFilter extends OncePerRequestFilter {
	protected static Logger logger = LoggerFactory.getLogger(LoginOutFilter.class);
	private String ssoLoginUrl;
	private String ssoVerfiyUrl;
	private ThreadLocal<TokerAuthenticator> threadLocal;
	
	
	public void init(FilterConfig filterConfig) {
		// TODO Auto-generated method stub
		this.ssoLoginUrl = filterConfig.getInitParameter("ssoLoginUrl");
		this.ssoVerfiyUrl = filterConfig.getInitParameter("ssoVerfiyUrl");
		threadLocal=new ThreadLocal<TokerAuthenticator>() {

			@Override
			protected TokerAuthenticator initialValue() {
				// TODO Auto-generated method stub
				return new TokerAuthenticator();
			}
			
		};
	}

	/**
	 * 所有请求前 0.获取是否已经登录 1.如果是从sso登录成功后带回token,则获取token去sso验证后保存
	 * 
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		logger.info(request.getSession() + "==>Requested SessionId:" + request.getRequestedSessionId());
		User user = (User) request.getSession().getAttribute("userInfo");
		
		
		if (user != null) {
			filterChain.doFilter(request, response);// 继续执行
			return;
		}
		// 1.获取token,说明是是从sso登录成功后回来的，则去sso验证或自动登录
		String token = request.getParameter("token");
		AuthenticatorRlt rlt;
		if (token != null) {
			// 去sso 验证token
			rlt =threadLocal.get().validate(token, ssoVerfiyUrl);
			user=new ObjectMapper().readValue(rlt.getUserInfo(),User.class);
			if (rlt!=null&&rlt.isVaild()) {// 如果user为空，则表明token invide
				logger.info("去sso验证并设置登录用户:" + user);
				request.getSession().setAttribute("userInfo", user);
				filterChain.doFilter(request, response);// 继续执行
				return;// 自动登录后继续执行当前业务
			}

		}
		logger.info("sso login");
		response.sendRedirect(
				ssoLoginUrl + "?backurl=" + URLEncoder.encode(request.getRequestURL().toString(), "UTF-8")); // 转向sso登录
		return;
	}

	

}
